import 'package:demo1223/routers/application.dart';
import 'package:flutter/material.dart';
import 'package:provide/provide.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../routers/application.dart';
import '../pages/toast/toast.dart';
import './index_page.dart';
import '../service/service_method.dart';
import 'package:dio/dio.dart';
import '../config/servcie.dart';
import '../provide/gettoken.dart';

class Loginpage extends StatefulWidget {
  @override
  _LoginpageState createState() => _LoginpageState();
}

class _LoginpageState extends State<Loginpage> {
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool _isClickEye = true;
  Color _eyeColor;
  TextEditingController _usernameController;
  TextEditingController _userpasswordController;
  FocusNode _fdUserName = FocusNode();
  FocusNode _fdUserPassWord = FocusNode();
  var _password = ''; //密码
  var _username = ''; //账号
  @override
  void initState() {
    super.initState();
    _usernameController = TextEditingController();
    _fdUserName.addListener(_focusNodeListener);
    _userpasswordController = TextEditingController();
    _fdUserPassWord.addListener(_focusNodeListener);
    _usernameController
      ..addListener(() {
        print(_usernameController.text);
        setState(() {});
      });
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    // 移除焦点监听
    _fdUserName.removeListener(_focusNodeListener);
    _fdUserPassWord.removeListener(_focusNodeListener);
    _usernameController.dispose();
    super.dispose();
  }

  Future<Null> _focusNodeListener() async {
    if (_fdUserName.hasFocus) {
      print('用户获取焦点');
      _fdUserPassWord.unfocus();
    }
    if (_fdUserPassWord.hasFocus) {
      print('用户密码获取焦点');
      _fdUserName.unfocus();
    }
  }

  String validatePassWord(value) {
    if (value.isEmpty) {
      return '密码不能为空';
    } else if (value.trim().length < 6 || value.trim().length > 18) {
      return '密码长度不正确';
    }
    return null;
  }

  String validateUserName(value) {
    // 正则匹配手机号
    print(value);
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    if (value.isEmpty) {
      return '用户名不能为空!';
    } else if (!exp.hasMatch(value)) {
      return '请输入正确手机号';
    }
    return null;
  }

  Widget build(BuildContext context) {
    // aaaaaa();
    return Container(
      decoration: BoxDecoration(
          image: DecorationImage(
             image: AssetImage('image/a.png'),
             fit: BoxFit.cover,
             
          )
      ),
      child:  Scaffold(
        backgroundColor: Colors.transparent, //把scaffold的背景色改成透明
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0, //把appbar的背景色改成透明
      ),
      resizeToAvoidBottomPadding: false,
      body: Container(
        child: Column(
          children: <Widget>[_logingroup()],
        ),
      ),
    ),
    );
     
  }

  Widget _logingroup() {
    return Container(
      margin: EdgeInsets.only(left: 20, right: 20),
      child: Column(
        children: <Widget>[
          _usernames(),
          _loginBtn(),
        ],
      ),
    );
  }

  Widget _usernames() {
    return Container(
      margin: EdgeInsets.only(top: 140),
      child: Form(
        key: _formKey,
        child: Column(
          children: <Widget>[
            Container(
              height: 90.0,
              child: TextFormField(
                controller: _usernameController,
                focusNode: _fdUserName,
                validator: validateUserName,
                onSaved: (String value) {
                  _username = value;
                },
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                  labelText: "手机号",
                  hintText: "请输入手机号",
                ),
              ),
            ),
            Container(
              height: 90.0,
              child: TextFormField(
                obscureText: _isClickEye,
                focusNode: _fdUserPassWord,
                validator: validatePassWord,
                onSaved: (String value) {
                  _password = value;
                },
                decoration: InputDecoration(
                  labelText: "密码",
                  hintText: "请输入密码",
                  suffixIcon: IconButton(
                    icon: Icon(Icons.remove_red_eye,color: _eyeColor,),
                    onPressed: (){
                      setState(() {
                         _isClickEye = !_isClickEye;
                _eyeColor = _isClickEye ? Colors.grey: Colors.blue;
                      });
                    },
                  )
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _loginBtn() {
    return Container(
      margin: EdgeInsets.only(left: 20, right: 20, top: 20),
      height: 45.0,
      width: 600.0,
      child: RaisedButton(
        color: Colors.blue[300],
        child: Text(
          '登录',
          style: Theme.of(context).primaryTextTheme.headline,
        ),
        shape:
            RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
        onPressed: () {
          _fdUserName.unfocus();
          _fdUserPassWord.unfocus();
          if (_formKey.currentState.validate()) {
            //只有输入通过验证，才会执行这里
            _formKey.currentState.save();
            //todo 登录操作
            print("$_username + $_password");
            getlogin();
          }
        },
      ),
    );
  }

  Widget _imgs() {
    return Container(
      child: Image.asset("image/top.png"),
    );
  }

  void getlogin() async {
    print('11111111111111111111111111111');
    print(_username);
    print(_password);
    var formData = {'username': _username, 'password': _password};
    print(formData);
    await DioUtil.request('userLogin', formData: formData).then((val) => {
          print(val),
          if (val != null)
            {
              Toast.show('登录成功'),
               Provide.value<Gettoken>(context).settoken(val['access_token']),
               print(val['access_token']),
               Navigator.of(context).pushAndRemoveUntil(
               MaterialPageRoute(builder: (context) => Indexpage()), (route) => route == null)
            }
          else
            {print('登录失败'),Toast.show('登录失败,账号或者密码错误'),}
            
        });
  }
}